package com.smartstate.gateway.handle;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler;
import org.springframework.cloud.gateway.support.NotFoundException;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ResponseStatusException;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.HashMap;
import java.util.Map;

/**
 * 网关异常通用处理器，只作用在webflux 环境下 , 优先级低于 ResponseStatusExceptionHandler 执行
 * @author runner-up
 */
@Slf4j
@Order(-1)
@Configuration
@RequiredArgsConstructor
public class GlobalExceptionHandler implements ErrorWebExceptionHandler {
	private final ObjectMapper objectMapper;

	@Override
	public Mono<Void> handle(ServerWebExchange exchange, Throwable ex) {
		ServerHttpResponse response = exchange.getResponse();

		ResponseStatusException responseStatusException = null;

		if (exchange.getResponse().isCommitted()) {
			return Mono.error(ex);
		}

		String msg;

		if (ex instanceof NotFoundException) {
			msg = "服务未找到";
		} else if (ex instanceof ResponseStatusException) {
			responseStatusException = (ResponseStatusException) ex;
			msg = responseStatusException.getMessage();
		} else {
			msg = "内部服务器错误";
		}

		log.error("[网关异常处理]请求路径:{},异常信息:{}", exchange.getRequest().getPath(), ex.getMessage());

		response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
		response.setStatusCode(HttpStatus.OK);

		if (responseStatusException != null) {
			ResponseStatusException finalResponseStatusException = responseStatusException;
			return response.writeWith(Mono.fromSupplier(() -> getDataBuffer(response, msg, finalResponseStatusException.getStatus().value())));
		} else {
			return response.writeWith(Mono.fromSupplier(() -> getDataBuffer(response, msg, 500)));
		}


	}

	private DataBuffer getDataBuffer(ServerHttpResponse response, String msg, int status) {
		DataBufferFactory bufferFactory = response.bufferFactory();
		Map<String, Object> map = new HashMap<>(2);
		map.put("status", status);
		map.put("msg", msg);
		return bufferFactory.wrap(JSON.toJSONBytes(map));
	}

}
